import { FC, useState } from "react";
import styles from "../List/common.module.scss";
import {
  Empty,
  Typography,
  Table,
  Tag,
  Space,
  Button,
  Modal,
  Spin,
  message,
} from "antd";
import { Key } from "antd/es/table/interface";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import ListSearch from "../../../components/ListSearch";
import useLoadQuestionList from "../../../hooks/useLoadQuestionList";
import ListPage from "../../../components/ListPage";
import { useRequest, useTitle } from "ahooks";
import {
  deleteQuestionsService,
  updateQuestionService,
} from "../../../services/question";

const { Title } = Typography;

const Trash: FC = () => {
  useTitle("小可问卷 | 回收站");

  const {
    loading,
    data = { list: [], total: 0 },
    refresh,
  } = useLoadQuestionList({
    isDeleted: true,
  });
  const { list = [], total = 0 } = data;
  // 记录选中的 id
  const [selectedIds, setSelectedIds] = useState<Key[]>([]);

  const tableColumns = [
    {
      title: "标题",
      dataIndex: "title",
    },
    {
      title: "是否发布",
      dataIndex: "isPublished",
      render: (isPublished: boolean) => (
        <span>
          {isPublished ? (
            <Tag color="processing">已发布</Tag>
          ) : (
            <Tag>未发布</Tag>
          )}
        </span>
      ),
    },
    {
      title: "答卷数量",
      dataIndex: "answerCount",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
    },
  ];

  const onRowSelectionChange = (selectedRowKeys: Key[]) => {
    setSelectedIds(selectedRowKeys);
  };

  const { loading: resoverLoading, run: handleRecover } = useRequest(
    async () => {
      for await (const id of selectedIds) {
        await updateQuestionService(id as string, { isDeleted: false });
      }
    },
    {
      manual: true,
      // debounceWait: 500,
      onSuccess() {
        message.success("恢复成功");
        setSelectedIds([]);
        refresh();
      },
    }
  );

  const recoverPaper = () => {
    Modal.confirm({
      title: "是否要恢复选中试卷？",
      icon: <ExclamationCircleOutlined />,
      onOk() {
        handleRecover();
      },
    });
  };

  const { loading: deleteLoading, run: deleteQuestion } = useRequest(
    async () => await deleteQuestionsService(selectedIds as string[]),
    {
      manual: true,
      onSuccess() {
        message.success("删除成功");
        setSelectedIds([]);
        refresh();
      },
    }
  );

  const deletePaper = () => {
    Modal.confirm({
      title: "是否要彻底删除选中试卷？",
      icon: <ExclamationCircleOutlined />,
      onOk() {
        deleteQuestion();
      },
    });
  };

  return (
    <div>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>回收站</Title>
        </div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      <div className={styles.content}>
        {loading && (
          <div style={{ textAlign: "center" }}>
            <Spin />
          </div>
        )}
        {!loading && list.length === 0 && <Empty description="暂无数据" />}
        {list.length > 0 && (
          <>
            <div style={{ marginBottom: "16px" }}>
              <Space>
                <Button
                  disabled={selectedIds.length === 0}
                  type="primary"
                  loading={resoverLoading}
                  onClick={recoverPaper}
                >
                  恢复
                </Button>
                <Button
                  disabled={selectedIds.length === 0}
                  type="primary"
                  danger
                  loading={deleteLoading}
                  onClick={deletePaper}
                >
                  彻底删除
                </Button>
              </Space>
            </div>
            <Table
              dataSource={list}
              columns={tableColumns}
              pagination={false}
              rowKey={(q) => q._id}
              rowSelection={{
                type: "checkbox",
                onChange: onRowSelectionChange,
              }}
            ></Table>
          </>
        )}
      </div>
      <div className={styles.footer}>
        <ListPage total={total} />
      </div>
    </div>
  );
};

export default Trash;
